<template>
  <div style="width: 48%; height: 320px" ref="chartRef"></div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick, onBeforeUnmount, computed } from 'vue'
import echarts from "@/plugins/echarts";
import type { ECOption } from '@/plugins/echarts'
import { UserData } from '@/types/statistics'

const props = defineProps<{
  userData: UserData
}>()
const userData = ref(props.userData)
// 图表dom实例
const chartRef = ref<HTMLElement | null>(null)
let resizeObserver: ResizeObserver | null = null
let chart: echarts.ECharts

const splitDateList = computed(() => (userData.value.dateList ? userData.value.dateList.split(',') : []))

const splitNewUserList = computed(() => (userData.value.newUserList ? userData.value.newUserList.split(',') : []))

const splitTotalUserList = computed(() => (userData.value.totalUserList ? userData.value.totalUserList.split(',') : []))
const initChart = () => {
  chart = echarts.init(chartRef.value, 'purple-passion')
  chart.setOption<ECOption>({
    title: {
      text: '用户统计',
      left: '10',
      top: '15',
      textStyle: {
        fontSize: '16px',
      },
    },
    legend: {
      show: true,
      orient: 'horizontal',
      x: 'center',
      y: '20',
      itemGap: 10,
      data: ['新增用户', '总用户'],
    },
    grid: {
      top: '20%',
      left: '30',
      right: '30',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: splitDateList.value,
      boundaryGap: false,
      axisLine: {
        //X轴线颜色
        lineStyle: {
          color: '#666',
          width: 1, //x轴线的宽度
        },
      },
    },
    tooltip: {
      trigger: 'axis',
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '新增用户',
        data: splitNewUserList.value,
        type: 'line',
        smooth: true,
        showSymbol: false,
      },
      {
        name: '总用户',
        data: splitTotalUserList.value,
        type: 'line',
        smooth: true,
        showSymbol: false,
      },
    ],
  })
  if (!resizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      if (chart) {
        chart.resize()
      }
    })
    resizeObserver.observe(chartRef.value!)
  }
}
onMounted(() => {
  initChart()
})
onBeforeUnmount(() => {
  if (chart) {
    echarts.dispose(chart)
  }
})
watch(
  () => props.userData,
  (newVal, _oldVal) => {
    nextTick(() => {
      userData.value = newVal
      echarts.dispose(chart)
      initChart()
    })
  },
  { immediate: true },
)
</script>
<style scoped lang="scss">
#main {
  background: #fff;
  border-radius: 5px;
}
</style>
